package com.restaurant.application.coupon;

import com.google.common.base.Strings;
import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.commonunits.utils.DateTimeUtils;
import com.nebutown.commonunits.utils.SnowFlake;
import com.nebutown.generation.basictype.UID;
import com.restaurant.application.coupon.support.AbstractCoupon;
import com.restaurant.application.coupon.support.CouponData;
import com.restaurant.application.customer.Customer;
import com.restaurant.application.customer.support.CustomerData;
import com.restaurant.application.indexes.couponlist.AssistCouponList;
import com.restaurant.application.indexes.couponlist.mysql.CouponListBean;
import com.restaurant.application.indexes.couponlist.mysql.CouponListCriteria;
import com.restaurant.application.indexes.couponlist.mysql.CouponListImpl;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListBean;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListCriteria;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListImpl;
import com.restaurant.application.minifacade.data.CardBO;
import com.restaurant.application.qrcode.QrCode;
import com.restaurant.application.util.Constant;
import com.restaurant.application.util.WeChatCode;
import com.restaurant.application.util.wx.WXLogin;

import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
public class CouponImpl extends AbstractCoupon {
    @Override
    public View getFullView() {
        return null;
    }

    @Override
    public View getViewLead(ViewSpec viewSpec) {
        return null;
    }

    @Override
    public String init(CouponData data) {

//        生成二维码
        UID qrUid = createNode(QrCode.class.getName()).getId();
        String qrUrl = WeChatCode.getminiQr(COUPON_NUMBER + data.getNumber(), WXLogin.getAccessToken().getAccess_token());
        getUnit(QrCode.class, qrUid).createQr(qrUrl, getId(), data.getNumber(), 0);

        UID customerUid = getGate();

        getData()
                .withId(SnowFlake.findUniqueId())
                .withType(data.getType())
                .withNumber(data.getNumber())
                .withModality(data.getModality())
                .withFullMoney(data.getFullMoney())
                .withMinusMoney(data.getMinusMoney())
                .withCreateTime(DateTimeUtils.getCurrentMillisecond())
                .withQrCodeUid(qrUid)
                .withQrCodeUrl(qrUrl)
                .withShopUid(data.getShopUid())
                .withShopName(data.getShopName())
                .withCouponManageUid(data.getCouponManageUid())
                .withCouponState(STATE_NOT_USED)
                .withVersion(0);

        if (Objects.nonNull(customerUid)) {
            CustomerData customerData = getUnit(Customer.class, customerUid).findData();
            if (Objects.nonNull(customerData)) {
                addCustomer(customerData, customerUid);
            }
        }

        perfect(data);
        CouponListBean bean = getSingleton(AssistCouponList.class).createBean(getId(), getData());
        if (Objects.nonNull(bean)) {
            getIndex(CouponListImpl.class).insert(bean);
        }
        return Constant.SUCCESS;
    }

    private void addCustomer(CustomerData customerData, UID uid) {
        int version = getData().getVersion() + 1;
        getData()
                .withCurrentCustomerId(customerData.getId())
                .withCurrentCustomerName(customerData.getNickName())
                .withCurrentPhone(customerData.getPhone())
                .withCurrentCustomerUid(uid)
                .withVersion(version);
        if (Objects.isNull(getData().getCustomerUid())) {
            getData()
                    .withCustomerId(customerData.getId())
                    .withCustomerName(customerData.getNickName())
                    .withCustomerUid(uid)
                    .withPhone(customerData.getPhone());
        }
    }

    @Override
    public String update(CouponData data) {
        perfect(data);
        return Constant.SUCCESS;
    }

    private String getStr() {
        if (STATE_USED.equals(getData().getState())) {
            return "该券已使用啦~";
        }
        if (STATE_NOT_OVERTIME.equals(getData().getState())) {
            return "该券已过期啦~";
        }
        return null;
    }

    @Override
    public String confirmUse(String id) {
        String str = getStr();
        if (!Strings.isNullOrEmpty(str)) {
            return str;
        }
//        todo 后台用户不完善，所以用户的uid and  name 未获取到
        getData()
                .withCouponState(STATE_USED)
                .withUserId(id)
                .withUsedCustomerId(getData().getCurrentCustomerId())
                .withUsedCustomerUid(getData().getCurrentCustomerUid())
                .withUsedCustomerName(getData().getCurrentCustomerName())
                .withUsedPhone(getData().getCurrentPhone())
                .withUsedTime(DateTimeUtils.getCurrentMillisecond());
        return Constant.SUCCESS;
    }

    @Override
    public String confirmReceive(int version) {
        if (version != getData().getVersion()) {
            return "改券已领取！";
        }
        UID customerUid = getGate();
        int totalAmount = getIndex(CouponListImpl.class).count(new CouponListCriteria().withCurrentCustomerUidEquals(customerUid.value()));
        List<CouponManageListBean> beans = getIndex(CouponManageListImpl.class)
                .search(new CouponManageListCriteria().withCouponManageUidEquals(getData().getCouponManageUid()), null, 1);
        if (beans.size() > 0) {
            if (totalAmount >= Integer.parseInt(beans.get(0).getLimitAccount())) {
                return "您拥有的数量已达上线";
            }
        } else {
            return "该券不存在";
        }
        String str = getStr();
        if (!Strings.isNullOrEmpty(str)) {
            return str;
        }

        CustomerData customerData = getUnit(Customer.class, customerUid).findData();

        addCustomer(customerData, customerUid);
        return Constant.SUCCESS;
    }

    @Override
    public CardBO getCardBean() {
        CouponData data = getData();
        return new CardBO()
                .withCardId(data.getNumber())
                .withContent(data.getModality())
                .withEndTime(DateTimeUtils.toTime(data.getEndTime()))
                .withErCode(data.getQrCodeUrl())
                .withRemark(data.getRemarks())
                .withCardType(data.getType())
                .withVersion(data.getVersion());
    }

    @Override
    public CouponData findData() {
        return getData();
    }

    private void perfect(CouponData data) {
        getData().withModifyTime(DateTimeUtils.getCurrentMillisecond());
        if (Objects.nonNull(data.getEndTime())) {
            getData().withEndTime(data.getEndTime());
        }
        if (!Strings.isNullOrEmpty(data.getRemarks())) {
            getData().withRemarks(data.getRemarks());
        }
        if (!Strings.isNullOrEmpty(data.getState())) {
            getData().withState(data.getState());
        }
        if (!Strings.isNullOrEmpty(data.getCouponState())) {
            getData().withCouponState(data.getCouponState());
        }
    }

    @Override
    public CouponListBean getCouponUidDataForCouponList(CouponListBean bean) {
        return getSingleton(AssistCouponList.class).updateBean(getId(), getData(), bean);
    }
}
